from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from myapp.Ser import Book_sortModelSerializer, BooksModelSerializer
from myapp.models import Book_sort, Books


class FenLeiAPI(APIView):
    def get(self, request):
        data = Book_sort.objects.all()
        all_data = Book_sortModelSerializer(data, many=True)
        return Response(all_data.data)


class BooksAPI(APIView):
    def get(self, request):
        id = request.GET.get('id')
        fid = request.GET.get('fid')
        if fid:
            ser = Books.objects.filter(eg=id)
            page = Paginator(ser, 2)
            page1 = page.page(fid)
            all_data = BooksModelSerializer(page1, many=True)
            return Response({
                'data': all_data.data,
                'page_range': [i for i in page.page_range]
            })
        else:
            data = Books.objects.all()
            all_data = BooksModelSerializer(data, many=True)
            return Response(all_data.data)


class OrderMoney(APIView):
    def get(self, request):
        type = request.GET.get('type')
        if type == '1':
            data = Books.objects.order_by('-' + 'price')
            all_data = BooksModelSerializer(data, many=True)
            return Response(all_data.data)
        else:
            data = Books.objects.order_by('price')
            all_data = BooksModelSerializer(data, many=True)
            return Response(all_data.data)


class Show(APIView):
    def get(self, request):
        meg = request.GET.get('meg')
        data = Books.objects.filter(name__contains=meg).all()
        all_data = BooksModelSerializer(data, many=True)
        return Response(all_data.data)
